const db = require('./server/config/database')

async function testRouteLogic () {
  try {
    console.log('=== 测试路由逻辑 ===')

    // 模拟请求参数
    const query = {
      category: undefined,
      sort: 'updated_at',
      search: undefined,
      limit: 20,
      offset: 0
    }

    console.log('1. 构建查询...')
    let sqlQuery = 'SELECT * FROM novels WHERE 1=1'

    const params = []

    // 按分类筛选
    if (query.category) {
      sqlQuery += ' AND category = ?'
      params.push(query.category)
    }

    // 搜索功能
    if (query.search) {
      sqlQuery += ' AND (title LIKE ? OR description LIKE ? OR author LIKE ?)'
      params.push(`%${query.search}%`, `%${query.search}%`, `%${query.search}%`)
    }

    // 排序
    switch (query.sort) {
      case 'popular':
        sqlQuery += ' ORDER BY view_count DESC'
        break
      case 'latest':
        sqlQuery += ' ORDER BY updated_at DESC'
        break
      case 'rating':
        sqlQuery += ' ORDER BY rating DESC'
        break
      default:
        sqlQuery += ' ORDER BY updated_at DESC'
    }

    // 分页
    sqlQuery += ' LIMIT ? OFFSET ?'
    params.push(query.limit, query.offset)

    console.log('2. 执行查询...')
    console.log('SQL:', sqlQuery)
    console.log('参数:', params)

    const novels = await db.query(sqlQuery, params)
    console.log(`查询结果: ${novels.length} 本小说`)

    // 处理数据格式
    const formattedNovels = novels.map(novel => ({
      ...novel,
      tags: novel.tags || []
    }))

    console.log('3. 格式化结果...')
    formattedNovels.slice(0, 2).forEach(novel => {
      console.log(`- ${novel.title} (${novel.author})`)
      console.log(
        `  状态: ${novel.status}, 标签: ${JSON.stringify(novel.tags)}`
      )
    })

    const result = {
      success: true,
      data: formattedNovels,
      total: formattedNovels.length
    }

    console.log('\n✅ 路由逻辑测试成功！')
    console.log('最终结果结构:', {
      success: result.success,
      dataCount: result.data.length,
      total: result.total
    })
  } catch (error) {
    console.error('❌ 路由逻辑测试失败:', error)
  } finally {
    process.exit(0)
  }
}

testRouteLogic()
